import 'dart:convert';

import 'package:spring_fairy/api/api.dart';
import 'package:spring_fairy/api/user_store.dart';
import 'package:spring_fairy/model/mood_diary.dart';

class DiaryAPI extends API {
  Future<MoodDiary?> writeDiary(MoodDiary diary) async {
    var response = await sendJSONPostRequest("/mood-diaries/write", diary.toJson());
    if(response == null) {
      return null;
    }
    try {
      return MoodDiary.fromJson(json.decode(response));
    } catch(_) {
      return null;
    }
  }

  Future<List<MoodDiary>> getAllDiary() async {
    var response = await sendGETRequest("/mood-diaries/${UserStore.user!.id!}/list");
    if(response == null) {
      return [];
    }
    var result = <MoodDiary>[];
    try {
      var list = json.decode(response);
      for(var ele in list) {
        result.add(MoodDiary.fromJson(ele));
      }
      return result;
    } catch(_) {
      return result;
    }
  }

  Future<MoodDiary?> update(MoodDiary diary)  async {
      var response = await sendJSONPostRequest("/mood-diaries/update/${diary.id!}", diary.toJson());
      if(response == null) {
        return null;
      }
      try {
        return MoodDiary.fromJson(json.decode(response));
      } catch(_) {
        return null;
      }
  }

}